<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>gnerator 函数</title>
  <style>
    body {
      width: 100%;
      height: 100%;

    }

    .red {
      width: 80%;
      height: 400px;
      background: red;
      font-size: 30px;
    }
  </style>
</head>

<body id="a">
  <div class="red" id="red">


  </div>

  <input type="search"></input>
</body>
<script>

  // gnerator 函数异步编程
  function * getStudentInfo({ studentId }) {
    let student = yield getStudentById(studentId);
    let service = yield getStudentServicesById(studentId)
    return [student, service];
  }

  function getStudentById(studentId) {
    let student = new Promise(function (resolve) {
      setTimeout(function () {
        resolve({ id: studentId, name: 'lame', sex: '1' })
      })
    })
    return student;
  }

  function getStudentServicesById(studentId) {
    let service = new Promise(function (resolve) {
      setTimeout(function () {
        resolve({ id: studentId, services: ['免费edu', '食堂饭卡', '校园网'] })
      })
    })
    return service;

  }

  // 这种还是手动执行，现在让它自动执行
  let student = getStudentInfo({studentId:0});
  console.log(student.next().value);
   student.next().value.then(function(data){
      return student.next(data).value;  // 将结果返回给下一次的next 的data 值
   }).then(function(data){
       console.log(data)
      console.log(student.next(data))
   })

  // 自动串联执行器
  function autoMachine(gen, args = {}) {
    let genIterator = gen(args);
    return new Promise(function (resolve, reject) {
      function next(data) {
        let p = genIterator.next(data);
        if (p.done) return resolve(p.value);
        p.value.then(function (data) {
          return next(data)
        })
      }
      next()
    })

  }

  // 并行, 将多个promise 用Promise.all 转成一个并行
  function* getInfo({ studentId }){
    let [student, service] = yield Promise.all([getStudentById(studentId),getStudentServicesById(studentId)])
    return [student, service];
  }

  // autoMachine(getInfo, { studentId: 333 }).then(function (data) {
  //   console.log(data)
  // })
  



</script>

</html>